import { GameEventData, GameEventType, BrickPartyBlock, BlockAnimationState } from "../bean/GameBean";
import { ReceivedMessageBean } from "../net/MessageBaseBean";
import { EventType } from "../common/EventCenter";
import { GameMgr } from "../common/GameMgr";
import GamePageController from "./GamePageController";

/**
 * 简化的游戏事件处理器
 * 专门处理方块动画相关的GameFrame消息
 */
export class SimpleGameEventHandler {
    private gamePageController: GamePageController | null = null;
    
    constructor() {}
    
    /**
     * 设置游戏页面控制器
     */
    public setGamePageController(controller: GamePageController): void {
        this.gamePageController = controller;
       
    }
    
    /**
     * 注册WebSocket消息处理器
     */
    public registerWebSocketHandlers(): void {
        GameMgr.Event.AddEventListener(EventType.ReceiveMessage, this.onReceiveMessage, this);
       
    }
    
    /**
     * 处理接收到的WebSocket消息
     */
    private onReceiveMessage(messageBean: ReceivedMessageBean): void {
        // 这里不再处理 GameFrame，避免与 GamePageController.handleGameFrame 重复驱动
        if (messageBean.msgId === "GameFrame") {
            return;
        }
        // 其他消息类型按需扩展
    }
    
    /**
     * 处理GameFrame消息
     */
    private handleGameFrame(frameData: any): void {
        
        if (!frameData) {
            console.error("[SimpleGameEventHandler] frameData为空");
            return;
        }
        
        if (!frameData.gameEvents) {
            
            return;
        }
        
        if (!Array.isArray(frameData.gameEvents)) {
            console.error("[SimpleGameEventHandler] gameEvents不是数组:", frameData.gameEvents);
            return;
        }
        
       
        
        // 处理每个游戏事件
        for (let i = 0; i < frameData.gameEvents.length; i++) {
            const gameEvent = frameData.gameEvents[i];
            this.processGameEvent(gameEvent);
        }
    }
    
    /**
     * 处理单个游戏事件
     */
    private processGameEvent(gameEvent: any): void {
       
        
        if (!gameEvent) {
            console.error("[SimpleGameEventHandler] gameEvent为空");
            return;
        }
        
        const anyEvent = gameEvent as any;
        const eventType = anyEvent.eventType;
        // 兼容两种结构：{ eventType, eventData: {...} } 或 { eventType, blocks, countDown, ... }
        const eventData = anyEvent.eventData || anyEvent;
        
        
        
        // 只处理方块相关的事件类型 (1-6)
        if (eventType >= 1 && eventType <= 6) {
            this.handleBlockEvent(eventType, eventData);
        } else {
           
        }
    }
    
    /**
     * 处理方块相关事件
     */
    private handleBlockEvent(eventType: number, eventData: any): void {
        // 支持 blockChanges 与 blocks 两种字段
        const blocksSource = eventData && (eventData.blockChanges || eventData.blocks);

        // 构造标准的GameEventData
        const gameEventData: GameEventData = {
            eventType: eventType,
            currentRound: (eventData && eventData.currentRound) || 1,
            countDown: (eventData && eventData.countDown) || 0,
            randomSeed: (eventData && eventData.randomSeed) || Math.floor(Math.random() * 100000),
            message: this.getEventMessage(eventType),
            blocks: this.parseBlockChanges(blocksSource)
        };
        
        // 转发给GamePageController
        this.forwardToController(gameEventData);
    }
    
    /**
     * 解析方块变化数据
     */
    private parseBlockChanges(blockChanges: any): BrickPartyBlock[] {
        if (!blockChanges || !Array.isArray(blockChanges)) {
            return [];
        }
        
        return blockChanges.map((block: any, index: number) => ({
            id: index + 1,
            x: block.x || 0,
            y: block.y || 0,
            blockType: 1,
            animationState: BlockAnimationState.NONE,
            animationDelay: 0
        }));
    }
    
    /**
     * 获取事件消息
     */
    private getEventMessage(eventType: number): string {
        switch (eventType) {
            case 1: return "游戏等待中";
            case 2: return "回合等待中";
            case 3: return "方块开始松动";
            case 4: return "方块开始掉落";
            case 5: return "方块开始补齐";
            case 6: return "游戏结束";
            default: return "未知事件";
        }
    }
    
    /**
     * 转发事件到控制器
     */
    private forwardToController(gameEventData: GameEventData): void {
        if (!this.gamePageController) {
            console.error("[SimpleGameEventHandler] GamePageController未设置，无法处理游戏事件");
            return;
        }
        
      
        this.gamePageController.handleGameEvent(gameEventData);
    }
    
    /**
     * 创建测试事件
     */
    public createTestShakingEvent(): void {
        const testEvent: GameEventData = {
            eventType: GameEventType.SHAKING,
            currentRound: 1,
            countDown: 2000,
            randomSeed: 12345,
            message: "测试方块松动",
            blocks: [
                { id: 1, x: 2, y: 3, blockType: 1, animationState: BlockAnimationState.NONE, animationDelay: 0 },
                { id: 2, x: 4, y: 5, blockType: 1, animationState: BlockAnimationState.NONE, animationDelay: 0 },
                { id: 3, x: 6, y: 7, blockType: 1, animationState: BlockAnimationState.NONE, animationDelay: 0 }
            ]
        };
        
       
        this.forwardToController(testEvent);
    }
    
    /**
     * 创建测试掉落事件
     */
    public createTestFallingEvent(): void {
        const testEvent: GameEventData = {
            eventType: GameEventType.FALLING,
            currentRound: 1,
            countDown: 500,
            randomSeed: 54321,
            message: "测试方块掉落",
            blocks: [
                { id: 1, x: 1, y: 1, blockType: 1, animationState: BlockAnimationState.NONE, animationDelay: 0 },
                { id: 2, x: 3, y: 4, blockType: 1, animationState: BlockAnimationState.NONE, animationDelay: 0 },
                { id: 3, x: 7, y: 8, blockType: 1, animationState: BlockAnimationState.NONE, animationDelay: 0 }
            ]
        };
        
       
        this.forwardToController(testEvent);
    }
    
    /**
     * 清理资源
     */
    public cleanup(): void {
        if (this.gamePageController) {
            GameMgr.Event.RemoveEventListener(EventType.ReceiveMessage, this.onReceiveMessage, this);
            this.gamePageController = null;
        }
    }
}
